package service

import (
	"errors"
	"fmt"
	"io"
	"net/http"
	"regexp"

	"file_explorer/common/log"
)

const CurVersion = "v0.1.0"

func CheckVersion() (curVersion, latestVersion, url string, err error) {
	curVersion = CurVersion

	resp, err := http.Get("https://gitee.com/travalone/file_explorer/raw/master/service/version.go")
	if err != nil {
		return
	}

	bytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return
	}

	reg, _ := regexp.Compile("const CurVersion = \"(.*)\"")
	matches := reg.FindStringSubmatch(string(bytes))
	if len(matches) < 2 {
		err = errors.New("extract version failed")
		return
	}

	latestVersion = matches[1]
	url = fmt.Sprintf("https://gitee.com/travalone/file_explorer/releases/download/%s/File%%20Explorer.exe", latestVersion)

	log.Debug("check version success, curVersion=%v, latestVersion=%v, url=%v", curVersion, latestVersion, url)

	return
}
